package com.imooc.springcloud;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author L
 */
@Slf4j
@Service
public class JwtService {

    // 生产环境要加密传入
    private static final String KEY = "changeIt";

    private static final String ISSUER = "yao";

    private static final long TOKEN_EXP_TIME = 60000;

    private static final String USER_NAME = "username";

    public String token(Account account) {
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME))
                .withClaim(USER_NAME, account.getUsername())
                .sign(algorithm);
        log.info("jwt" + account.getUsername());
        return token;
    }

    public boolean verify(String token, String username) {
        log.info("verifying jwt:" + username);
        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withClaim(USER_NAME, username)
                    .build();
            verifier.verify(token);
        } catch (Exception e) {
            log.error("auth failed", e);
            return false;
        }
        return true;
    }
}
